package com.psa.dialog;

import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.psa.element.Distributor;
import com.psa.system.R;
import com.psa.tool.IGeneralEventCallback;
import com.wxw.BaseLibrary.adapter.SpinnerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author david
 * @date 2016-06-23
 */
public class DistributorSelectorDialog extends DialogManager implements View.OnClickListener {
    private Spinner sp_distributor;
    private List<Distributor> distributorList = new ArrayList<Distributor>();
    private OnDistributorSelectedListener onDistributorSelectedListener;
    private IGeneralEventCallback onCancelListener;

    public DistributorSelectorDialog(Activity parent, List<Distributor> distributors) {
        parentActivity = parent;
        distributorList = distributors;
        initView();
    }

    @Override
    public void setTitle(String title) {
        this.title = title;
    }

    public void setOnDistributorSelectedListener(OnDistributorSelectedListener onDistributorSelectedListener) {
        this.onDistributorSelectedListener = onDistributorSelectedListener;
    }

    public void setOnCancelListener(IGeneralEventCallback onCancelListener) {
        this.onCancelListener = onCancelListener;
    }

    @Override
    public View initView() {
        layout = parentActivity.getLayoutInflater().inflate(R.layout.distributor_selector_dialog_layout, null);
        sp_distributor = (Spinner)layout.findViewById(R.id.sp_distributor);
        tv_title = (TextView)layout.findViewById(R.id.tv_title);
        ((Button)layout.findViewById(R.id.btn_ok)).setOnClickListener(this);
        ((Button)layout.findViewById(R.id.btn_cancel)).setOnClickListener(this);
        refreshDistributor();
        return layout;
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_cancel) {
            if (onCancelListener!=null)
                onCancelListener.finished(this, "canceled");
        } else {
            Distributor distributor = (Distributor)sp_distributor.getSelectedItem();
            if (onDistributorSelectedListener != null)
                onDistributorSelectedListener.onSelected(this, distributor);
        }
        if (dialog!=null)dialog.dismiss();
    }

    private void refreshDistributor() {
//        Cursor cursor = DBTool.getInstance().query("Select * From Distributor Where CustomerID='"
//                + SystemStatus.currentCustomer.getID().trim()+"' order by def");
//        distributorList = DBTool.convertCursorToList(cursor, Distributor.class);
        SpinnerAdapter<Distributor> adapter = new SpinnerAdapter<Distributor>(parentActivity, 0, distributorList, R.drawable.dropdown);
        sp_distributor.setAdapter(adapter);
    }

    public interface OnDistributorSelectedListener{
        void onSelected(Object sender, Distributor distributor);
    }
}
